package com.yeci.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.yeci.common.page.PageDomain;
import com.yeci.common.page.TableSupport;
import com.yeci.common.utils.SqlUtil;
import com.yeci.common.utils.StringUtil;
import com.yeci.entity.SysUser;
import com.yeci.mapper.SysUserMapper;
import com.yeci.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yeci
 * @since 2021-08-01
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

  @Autowired
  private SysUserMapper userMapper;

  @Override
  public SaTokenInfo login(SysUser sysUser) {
    // 根据用户名进行查询
    SysUser user = userMapper.selectByUserName(sysUser.getUsername());
    if(user == null){
      return null;
    }
    String salt = user.getSalt();
    String password = sysUser.getPassword();
    if(!SaSecureUtil.md5BySalt(password,salt).equals(user.getPassword())){
      return null;
    }
    // 密码校验成功后登录
    StpUtil.login(user.getId());
    // 获取当前登录用户Token信息
    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
    return tokenInfo;
  }

  @Override
  public List<SysUser> selectUserList(SysUser sysUser) {
    startPage();
    List<SysUser> sysUsers = userMapper.selectUserList(sysUser);
    return sysUsers;
  }

  /**
   * 设置请求分页数据
   */
  protected void startPage()
  {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();
    System.out.println(pageNum);
    System.out.println(pageSize);
    if (StringUtil.isNotNull(pageNum) && StringUtil.isNotNull(pageSize))
    {
      String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
      PageHelper.startPage(pageNum, pageSize, orderBy);
    }
  }
}
